//
//  HDComposeController.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/8.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit
import  SVProgressHUD
class HDComposeController: UIViewController {
    //记录属性 照片选择器的view是否显示
    private var isShowPhotoSelectorView = false
    //图片选择器选择的时候  不频繁切换键盘
    override func viewWillAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if isShowPhotoSelectorView{
            textView.resignFirstResponder()
        }
    }
    //让键盘成为第一响应者 一开就有键盘
    override func  viewDidAppear(animated: Bool) {
        super.viewDidDisappear(animated)
        textView.becomeFirstResponder()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        //设置UI
        prepareUI()
    }
    private func prepareUI(){
        //设置导航栏
        setNavigationBar()
        //设置textView
        setTitleView()
        //设置图片管理器
        setPhotoSeleted()
        //设置toolBar
        setToolBar()
        //设置微博长度
        setLengthTiplabel()
        //监听键盘的frame改变
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("WillChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
   
    }
    //通知回调
    @objc private func WillChangeFrame(notification:NSNotification){
        HDPrint("notification\(notification)")
        //键盘的frame
        let  frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //动画时间
        let  duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        //动画
        self.toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(-(ScreenH - frame.origin.y))
        }

        UIView.animateWithDuration(duration) { () -> Void in
          self.view.layoutIfNeeded()
        }
    }
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK -1.设置导航栏
    private func setNavigationBar(){
        //左边导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
        //右边导航栏
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("send"))
        navigationItem.rightBarButtonItem?.enabled = false
        //设置中间标题
        setTitle()
    }
    private func  setTitle(){
        //设置后缀
        let hasfix = "发微博"
        //拼接用户名
        if let  name = HDUserAccoutViewModel.userAccoutShare.userAccount?.screen_name{
            //创建label
            let label = UILabel(color: UIColor.blackColor(), fontsize: 16, numberOflines: 0)
            label.textAlignment = NSTextAlignment.Center
            //富文本属性 设置用户名的字体的颜色
            let  titleText = hasfix + " \n " + name
            let attributeText = NSMutableAttributedString(string: titleText)
            let  nameRange = (titleText as NSString).rangeOfString(name)
            let attrs = [NSFontAttributeName : UIFont.systemFontOfSize(11), NSForegroundColorAttributeName : UIColor.orangeColor()]
            attributeText.addAttributes(attrs, range: nameRange)
            label.attributedText = attributeText
            label.sizeToFit()
            navigationItem.titleView = label
        }else{
            navigationItem.title = hasfix
        }
    
    }
    //按钮监听方法
    @objc private  func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send(){
        let status = textView.emoticonText()
        //如果长度超过最大长度  提示用户
        if status.characters.count > statusMaxLength {
            SVProgressHUD.showErrorWithStatus("微博内容超过长度")
            SVProgressHUD.setDefaultMaskType(.Black)
            return
        }
    
        HDStatusViewModel.statusShare.sendStatus(status, image: photoSeletedVc.photos.first) { (error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送出错,稍后再发")
                return
            }
            SVProgressHUD.showErrorWithStatus("发送微博成功")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
                self.close()
            }
        }
    }
    
    //MARK -2.设置ToolBar
    private func setToolBar() {
        //添加到父控件
        view.addSubview(toolBar)
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        //创建一个空的items数组
        var items:[UIBarButtonItem] = []
        let itemsetting =  [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        //定义索引
//        var  index = 0
        //遍历创建items
        for  dict in itemsetting {
            let imageName = dict["imageName"]!
            let heightlightImageName = imageName + "_highlighted"
            let  action = dict["action"]
            let item = UIBarButtonItem.createBarButtonItem(imageName, highlightedIamgeName:  heightlightImageName, target: self, action: Selector(action!))
            items.append(item)
//            let btn = item.customView
//            btn!.tag = index
//            index++
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        //删除最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }
    //MARK -按钮监听方法
    @objc private func picture(){
        isShowPhotoSelectorView = true
        //更新的图片选择器的约束
        photoSeletedVc.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view)
        }
        UIView.animateWithDuration(animationCurtation) { () -> Void in
            self.view.layoutIfNeeded()
        }
        //键盘退下
        textView.resignFirstResponder()
    }
    @objc private func trend(){
        HDPrint("#")
    }
    @objc private func mention(){
         HDPrint("@")
    }
    @objc private func emoticon(button:UIButton){
        HDPrint("表情")
        //切换键盘  nil  默认是系统键盘
        textView.resignFirstResponder()
        //设置不同toolBar 
        var normalIamge : UIImage?
        var hightlightedImage: UIImage?
        textView.inputView =  textView.inputView == nil ? emoticonKeyboard :nil
        if textView.inputView == nil {
            normalIamge = UIImage(named: "compose_emoticonbutton_background")
            hightlightedImage = UIImage(named: "compose_add_background_highlighted")
        }else{
            normalIamge = UIImage(named: "compose_keyboardbutton_background")
            hightlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        button.setImage(normalIamge, forState: UIControlState.Normal)
        button.setImage(hightlightedImage, forState: UIControlState.Highlighted)
        
        
        //用延时给键盘切换事件
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
    }
    @objc private func add(){
         HDPrint("加号")
    }
    
    //MARK -3.设置TextView
    private func  setTitleView(){
        //添加到父控件
        view.addSubview(textView)
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    
    //MARK -4.设置微博的长度
    private let statusMaxLength = 140
    private func setLengthTiplabel(){
        view.addSubview(lengthTipLabel)
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            let margin = 4
            make.trailing.equalTo(toolBar).offset(-margin)
            make.bottom.equalTo(toolBar.snp_top).offset(-margin)
        }
        lengthTipLabel.text = "\(statusMaxLength)"
    }
    //MARK -5.设置图片选择器
    private func setPhotoSeleted(){

        let  photoView = photoSeletedVc.view
        self.view.addSubview(photoView)
        self.addChildViewController(photoSeletedVc)
        let height = UIScreen.mainScreen().bounds.height*0.6
        //添加约束
        photoView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(height)
            make.height.equalTo(height)
        }
    }
    

//MARK -懒加载
    private lazy var toolBar:UIToolbar = UIToolbar()
    private lazy var textView:HDComposeTextView = {
        let  textView = HDComposeTextView()
        //设置textView有回弹效果
        textView.alwaysBounceVertical = true
        //拖动textView会关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置占位文字
        textView.placeholderText = "分享新鲜事....."
        textView.font = UIFont.systemFontOfSize(30)
        //设置textView代理  改变导航栏右边按钮的交互状态
        textView.delegate = self
        return textView
    }()
    private lazy var  emoticonKeyboard:HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        keyboard.textView = self.textView
        return keyboard
    }()
    private lazy var lengthTipLabel :UILabel = UILabel(color: UIColor.lightGrayColor(), fontsize: 12)
    private lazy var photoSeletedVc: HDPhotoViewController = HDPhotoViewController()
}
extension  HDComposeController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        //计算剩余文本的长度
        let text = textView.emoticonText() //已经写的长度
        let length = statusMaxLength - text.characters.count //剩余长度
        lengthTipLabel.text = "\(length)"
        //如果长度小于零就红色
        lengthTipLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
    }
}
